﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using System.Text;
using Newtonsoft.Json;

namespace LawSuitUploadTask
{
    public partial class Form1 : Form
    {
        //word里的上传字段名链表
        private static ArrayList m_arrOriginTypes = new ArrayList();
        //
        private static Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();
        //真正的案件链表
        private static List<System.Collections.Generic.Dictionary<string, string>> m_arrRealTasks = new List<System.Collections.Generic.Dictionary<string, string>>();
        //子线程通知主线程更新界面
        private SynchronizationContext m_thSynContext = null;

        //server dictionary
        private HttpWorkRequestNS.DictionaryRespList m_srvTeamList;
        private HttpWorkRequestNS.DictionaryRespList m_srvTypeList;
        private HttpWorkRequestNS.DictionaryRespList m_srvLimitTimeList;
        private HttpWorkRequestNS.DictionaryRespList m_srvOwnerShipList;


        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            base.OnFormClosed(e);
            oWord.Quit();
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }

        public Form1()
        {
            InitializeComponent();
            //静默登录
            Login();
            //
            m_thSynContext = SynchronizationContext.Current;
            //
            InitListViewColumn();
            InitUploadTypesArray();
        }

        //-----------------------------以下两个函数是为了分辨出哪个是处理过的----------------------------------------
        private string GetCurrentCopeNum()
        {
            string sCurrentDir = System.Windows.Forms.Application.StartupPath;
            string sFilePath = string.Format("{0}\\config.ini", sCurrentDir);
            string data = OperateIniFile.ReadIniData("copenum", "num", sFilePath);
            return data;
        }

        private void SetCurrentCopeNum(string value)
        {
            string sCurrentDir = System.Windows.Forms.Application.StartupPath;
            string sFilePath = string.Format("{0}\\config.ini", sCurrentDir);
            OperateIniFile.WriteIniData("copenum", "num", value, sFilePath);
        }

        private void InitServerDictionaryData()
        {
            string resp1 = HttpWorkRequestNS.NetWorkUtils.HttpGetNetData("dictionary/team", new System.Collections.Generic.Dictionary<string, string>());
            m_srvTeamList = JsonConvert.DeserializeObject<HttpWorkRequestNS.DictionaryRespList>(resp1);

            string resp2 = HttpWorkRequestNS.NetWorkUtils.HttpGetNetData("dictionary/questionType", new System.Collections.Generic.Dictionary<string, string>());
            m_srvTypeList = JsonConvert.DeserializeObject<HttpWorkRequestNS.DictionaryRespList>(resp2);

            string resp3 = HttpWorkRequestNS.NetWorkUtils.HttpGetNetData("dictionary/rankOf12345", new System.Collections.Generic.Dictionary<string, string>());
            m_srvLimitTimeList = JsonConvert.DeserializeObject<HttpWorkRequestNS.DictionaryRespList>(resp3);

            string resp4 = HttpWorkRequestNS.NetWorkUtils.HttpGetNetData("dictionary/owershipOf12345", new System.Collections.Generic.Dictionary<string, string>());
            m_srvOwnerShipList = JsonConvert.DeserializeObject<HttpWorkRequestNS.DictionaryRespList>(resp4);

            //
            InitComboboxInfo();
        }

        private void Login()
        {
            System.Collections.Generic.Dictionary<string, string> param = new System.Collections.Generic.Dictionary<string, string>();
            param.Add("username", "admin");
            param.Add("password", "123456");
            param.Add("grant_type", "password");
            param.Add("scope", "all");
            param.Add("client_id", "municipal");
            param.Add("client_secret", "municipal");
            string response = HttpWorkRequestNS.NetWorkUtils.HttpPostNetData("oauth/token", param);
            //解析登录返回值
            HttpWorkRequestNS.LoginRespObj respJson = JsonConvert.DeserializeObject<HttpWorkRequestNS.LoginRespObj>(response);
            //插入頭信息
            string sheader = string.Format("{0} {1}", respJson.token_type, respJson.access_token);
            HttpWorkRequestNS.NetWorkUtils.SetHeaderInfo(sheader);

            //
            InitServerDictionaryData();
        }

        private void InitComboboxInfo()
        {
            //
            foreach (HttpWorkRequestNS.DictionaryRespItem item in m_srvLimitTimeList.data)
            {
                comboBox1.Items.Add(item.title);
            }
            comboBox1.SelectedIndex = 3;

            //
            foreach (HttpWorkRequestNS.DictionaryRespItem item in m_srvTeamList.data)
            {
                comboBox2.Items.Add(item.title);
            }
            comboBox2.SelectedIndex = 1;

            //
            foreach (HttpWorkRequestNS.DictionaryRespItem item in m_srvTypeList.data)
            {
                comboBox3.Items.Add(item.title);
            }
            comboBox3.SelectedIndex = 0;

            //
            foreach (HttpWorkRequestNS.DictionaryRespItem item in m_srvOwnerShipList.data)
            {
                comboBox4.Items.Add(item.title);
            }
            comboBox4.SelectedIndex = 0;
        }


        public void InitListViewColumn()
        {
            this.listView1.Columns.Add("市级编号", 160, HorizontalAlignment.Center); //
            this.listView1.Columns.Add("区级编号", 160, HorizontalAlignment.Center); //
            this.listView1.Columns.Add("案件类型", 200, HorizontalAlignment.Center); //
            this.listView1.Columns.Add("联系地址", 200, HorizontalAlignment.Center); //
            this.listView1.Columns.Add("来电电话", 150, HorizontalAlignment.Center); //
            this.listView1.Columns.Add("完成时间", 150, HorizontalAlignment.Center); //
            this.listView1.FullRowSelect = true;
        }

        public void InitUploadTypesArray()
        {
            this.CenterToScreen();

            m_arrOriginTypes.Add("信件编号");
            m_arrOriginTypes.Add("信件来源");
            m_arrOriginTypes.Add("来信人姓名");
            m_arrOriginTypes.Add("情绪");
            m_arrOriginTypes.Add("联系地址");
            m_arrOriginTypes.Add("联系电话");
            m_arrOriginTypes.Add("来电电话");
            m_arrOriginTypes.Add("来电时间");
            m_arrOriginTypes.Add("采集人");
            m_arrOriginTypes.Add("分类");
            m_arrOriginTypes.Add("信件主题");
            m_arrOriginTypes.Add("来电内容");
            m_arrOriginTypes.Add("转办部门");
            m_arrOriginTypes.Add("转办人");
            m_arrOriginTypes.Add("完成日期");
            m_arrOriginTypes.Add("转办意见");
            m_arrOriginTypes.Add("拟办意见");
            m_arrOriginTypes.Add("承办单位");
            m_arrOriginTypes.Add("办理时限");
            m_arrOriginTypes.Add("办理时间");
            m_arrOriginTypes.Add("办理情况");
        }

        //重要方法，从word中读取信息，并入栈map和arraylist
        public static void LoadWordLawSuitInfo(object fileName)
        {
            object oReadOnly = false;
            object oMissing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word.Document document = oWord.Documents.Open(ref fileName, ref oMissing, ref oReadOnly, ref oMissing, ref oMissing,
                            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            //
            Microsoft.Office.Interop.Word.Table table = document.Tables[1];
            int nRowsCount = table.Rows.Count;

            //一个案件就是一个dictionary
            System.Collections.Generic.Dictionary<string, string> dicMap = new System.Collections.Generic.Dictionary<string, string>();
            for (int i = 1; i != nRowsCount + 1; ++i)
            {
                Microsoft.Office.Interop.Word.Row row = table.Rows[i];
                //
                for (int j = 1; j != row.Cells.Count + 1; ++j)
                {
                    string keyText = table.Cell(i, j).Range.Text.ToString();
                    keyText = keyText.Replace("\r\a", "");

                    if (i == 1 && j == 1)
                    {
                        keyText = keyText.Replace("基本信息", "");
                        if (keyText == "")
                        {
                            dicMap.Add("市级编号", "无");
                        }
                        else
                        {
                            dicMap.Add("市级编号", keyText);
                        }
                    }


                    //如果发现是m_arrayUpTypes里的一种，就入栈
                    if (m_arrOriginTypes.Contains(keyText))
                    {
                        string typeVal = table.Cell(i, j + 1).Range.Text.ToString();
                        typeVal = typeVal.Replace("\r\a", "");
                        dicMap.Add(keyText, typeVal);
                    }
                }
            }
            //
            m_arrRealTasks.Add(dicMap);
        }


        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Multiselect = true;//等于true表示可以选择多个文件
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                string note = string.Format("共加载{0}个文档，请耐心等待。。。。", dlg.FileNames.Length);
                textBox15.Text = note;

                //开启线程，开始遍历
                Thread thread = new Thread(new ParameterizedThreadStart(LoadIOWordDoc));
                thread.Start(dlg.FileNames as object);
            }
        }

        public void LoadIOWordDoc(object paths)
        {
            string[] filePaths = paths as string[];
            foreach (object file in filePaths)
            {
                LoadWordLawSuitInfo(file);
            }
            m_thSynContext.Post(InsertDataListView, "");//子线程中通过UI线程上下文更新UI 
        }


        private void InsertDataListView(object obj)
        {
            textBox15.Text = "完成加载！";

            //
            string copenum = GetCurrentCopeNum();

            this.listView1.BeginUpdate();   //数据更新，UI暂时挂起，直到EndUpdate绘制控件，可以有效避免闪烁并大大提高加载速度
            this.listView1.Items.Clear();
            for (int i = 0; i < m_arrRealTasks.Count; i++)
            {
                System.Collections.Generic.Dictionary<string, string> dic = m_arrRealTasks[i];
                ListViewItem lvi = new ListViewItem();

                //如果信件编号在ini文件中出现过，证明是处理过的，不用再次处理，在列表中变为绿色
                if (copenum.Contains(dic["信件编号"]))
                {
                    lvi.ForeColor = System.Drawing.Color.ForestGreen;
                }
                else
                {
                    lvi.ForeColor = System.Drawing.Color.OrangeRed;
                }

                lvi.Font = new System.Drawing.Font("微软雅黑", 9.5F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));

                lvi.Text = dic["市级编号"];
                lvi.SubItems.Add(dic["信件编号"]);
                lvi.SubItems.Add(dic["分类"]);
                lvi.SubItems.Add(dic["联系地址"]);
                lvi.SubItems.Add(dic["来电电话"]);
                lvi.SubItems.Add(dic["完成日期"]);
                this.listView1.Items.Add(lvi);
            }

            this.listView1.EndUpdate();  //结束数据处理，UI界面一次性绘制。
        }

        //当前选中了的列表中的text
        private string m_currentSelText = "";

        private void listViewRowClicked(object sender, MouseEventArgs e)
        {
            //直接拿到市级单号
            m_currentSelText = this.listView1.SelectedItems[0].Text;
            //然后比对，取出所有数据
            List<System.Collections.Generic.Dictionary<string, string>> selectItem = m_arrRealTasks.Where(item => item["市级编号"] == m_currentSelText).ToList();
            System.Collections.Generic.Dictionary<string, string> dic = selectItem[0];
            textBox1.Text = dic["市级编号"];
            textBox2.Text = dic["信件编号"];
            textBox3.Text = dic["来信人姓名"];
            textBox4.Text = dic["联系地址"];
            textBox5.Text = dic["分类"];
            textBox6.Text = dic["联系电话"];
            textBox7.Text = dic["来电电话"];
            textBox8.Text = dic["采集人"];
            textBox9.Text = dic["来电时间"];
            textBox10.Text = dic["信件主题"];
            richTextBox1.Text = dic["来电内容"];
            textBox11.Text = dic["转办部门"];
            textBox12.Text = dic["转办人"];
            textBox13.Text = dic["完成日期"];
            textBox14.Text = dic["办理时限"];
            richTextBox2.Text = dic["转办意见"];
        }


        //提交案件至平臺
        private void button2_Click(object sender, EventArgs e)
        {
            string copeNum = GetCurrentCopeNum();
            if (copeNum.Contains(textBox2.Text))
            {
                MessageBox.Show("此案件已被处理过，请勿重复处理", "错误");
                return;
            }

            string upSrvLimitTimeText = comboBox1.Text;
            string upSrvTeamText = comboBox2.Text;
            string upSrvTypeText = comboBox3.Text;
            string upSrvOwnerText = comboBox4.Text;

            //根据文字过滤code
            List<HttpWorkRequestNS.DictionaryRespItem> listLimitTm = m_srvLimitTimeList.data.Where(item => item.title == upSrvLimitTimeText).ToList();
            List<HttpWorkRequestNS.DictionaryRespItem> listTeam = m_srvTeamList.data.Where(item => item.title == upSrvTeamText).ToList();
            List<HttpWorkRequestNS.DictionaryRespItem> listType = m_srvTypeList.data.Where(item => item.title == upSrvTypeText).ToList();
            List<HttpWorkRequestNS.DictionaryRespItem> listOwner = m_srvOwnerShipList.data.Where(item => item.title == upSrvOwnerText).ToList();

            //取出code
            string upSrvLimitTimeCode = listLimitTm[0].code;
            string upSrvTeamCode = listTeam[0].code;
            string upSrvTypeCode = listType[0].code;
            string upSrvOwnerCode = listOwner[0].code;

            //市级编号
            string upSrvCityNum = textBox1.Text;
            //区级编号
            string upSrvDistrictNum = textBox2.Text;
            //地址
            string upSrvAddress = textBox4.Text == "" ? "无" : textBox4.Text;
            //来电人姓名
            string upSrvCallPerson = textBox3.Text;
            //来电人电话
            string upSrvCallPhone = textBox7.Text;
            //来电内容
            string upSrvCallInfo = richTextBox1.Text;

            //组map param
            System.Collections.Generic.Dictionary<string, string> dicParam = new System.Collections.Generic.Dictionary<string, string>();
            dicParam.Add("workOrderNum", upSrvCityNum);
            dicParam.Add("areaOrderNum", upSrvDistrictNum);
            dicParam.Add("address", upSrvAddress);
            dicParam.Add("rankOf12345", upSrvLimitTimeCode);
            dicParam.Add("questionType", upSrvTypeCode);
            dicParam.Add("callerName", upSrvCallPerson);
            dicParam.Add("callerPhone", upSrvCallPhone);
            dicParam.Add("callerTime", textBox9.Text);
            dicParam.Add("ownership", upSrvOwnerCode);
            dicParam.Add("taskRemark", upSrvCallInfo);
            dicParam.Add("taskState", "caseState-2");
            dicParam.Add("contactPhone", textBox6.Text);
            dicParam.Add("collector", textBox8.Text);
            dicParam.Add("transferor", textBox12.Text);
            dicParam.Add("classification", textBox5.Text);
            dicParam.Add("transferOpinion", richTextBox2.Text);
            dicParam.Add("transferUnit", textBox11.Text);
            dicParam.Add("callerMood", textBox17.Text);
            dicParam.Add("proposedOpinions", "");
            dicParam.Add("areaDistributeTime", textBox9.Text);
            dicParam.Add("subject", textBox10.Text);

            string handleTime = textBox14.Text.Substring(0, textBox14.Text.IndexOf(' '));
            dicParam.Add("handleTime", handleTime);

            //
            if (upSrvOwnerText == "非权属")
            {
                dicParam.Add("nonOwnership", richTextBox3.Text);
            }
            if (upSrvOwnerText == "协同")
            {
                dicParam.Add("jointUnit", textBox16.Text);
            }
            if (upSrvOwnerText == "权属")
            {
                dicParam.Add("jobTeam", upSrvTeamCode);
            }


            //
            string sCurrentDir = System.Windows.Forms.Application.StartupPath;
            string sFilePath = string.Format("{0}\\1.jpg", sCurrentDir);
            string response = HttpWorkRequestNS.NetWorkUtils.HttpPostMultiPartData("http://123.206.73.108:90/api/HotLine", sFilePath, "1.jpg", "image/jpeg", dicParam);
            //
            HttpWorkRequestNS.NoDataRespObj obj = JsonConvert.DeserializeObject<HttpWorkRequestNS.NoDataRespObj>(response);
            if (obj.code == 0)
            {
                //
                string num = GetCurrentCopeNum();
                StringBuilder sb = new StringBuilder();
                sb.Append(num);
                sb.Append(upSrvDistrictNum);
                sb.Append(",");
                SetCurrentCopeNum(sb.ToString());
                //重新刷新列表
                InsertDataListView("");
                //
                MessageBox.Show("已提交12345案件至平台，成功！", "提示");
            }
        }

        private void OwnerComboboxSelectedChanged(object sender, EventArgs e)
        {
            string selectText = comboBox4.Text;
            //
            switch (selectText)
            {
                case "权属":
                    comboBox2.Visible = true;
                    label18.Visible = true;
                    //
                    label21.Visible = false;
                    richTextBox3.Visible = false;
                    //
                    label22.Visible = false;
                    textBox16.Visible = false;
                    break;
                case "非权属":
                    comboBox2.Visible = false;
                    label18.Visible = false;
                    //
                    label21.Visible = true;
                    richTextBox3.Visible = true;
                    //
                    //
                    label22.Visible = false;
                    textBox16.Visible = false;
                    break;
                case "协同":
                    comboBox2.Visible = false;
                    label18.Visible = false;
                    //
                    label21.Visible = false;
                    richTextBox3.Visible = false;
                    //
                    label22.Visible = true;
                    textBox16.Visible = true;
                    break;
            }

        }


    }
}
